const Controller = require('../prototype/Controller')
const { convertToObjectId } = require('../utils/db')
const { models } = require('../model')

class Tool extends Controller {
  constructor () {
    super()
    this.model = models.Tool
  }

  updateStatus () {
    return async (ctx) => {
      const { id, status } = ctx.request.body
      const result = await this.model.updateById(id, {
        $set: { status: status }
      })
      ctx.wrapper.succ(result)
    }
  }

  batchUpdateStatus () {
    return async (ctx) => {
      const query = this._getRequestQuery(ctx)
      const findQuery = {}
      const status = ctx.request.body.update.status
      if (status !== 0 && status !== 1) {
        return ctx.wrapper.error('PARAMETERS_ERROR', '状态参错错误，可选值为 Number(0) Number(1)')
      }
      if (query.tags && query.tags.length > 0) {
        findQuery.tags = {
          $in: convertToObjectId(query.tags)
        }
      }
      if (query.keywords) {
        findQuery.$or = [
          { name: { $regex: `${query.keywords}` } },
          { description: { $regex: `${query.keywords}` } }
        ]
      }
      const result = await this.model.coll.updateMany(findQuery, {
        $set: {
          status
        }
      })
      ctx.wrapper.succ(result)
    }
  }
}

module.exports = Tool
